import ITable, { ITableProps, ITableRef } from '@/components/Table';
import { OrderInfo, ReporterInfo } from '#/entity.ts';
import WorkOrderServices, { OrderListParams } from '@/api/services/workOrderServices.ts';
import { Button, Space, Tooltip } from 'antd';
import PermissionGuard from '@/components/PermissionGuard';
import { FormFieldType } from '@ycx/ui';
import { useQueries } from '@tanstack/react-query';
import { useCatch, useUserRole } from '@/hooks';
import EventCenterServices from '@/api/services/eventCenterServices.ts';
import { Page, Result } from '#/api.ts';
import DetailDrawer, {
  DetailDrawerRef,
} from '@/pages/workOrderManagement/components/DetailDrawer.tsx';
import { useMemo, useRef } from 'react';
import EditOrderStatusModal, {
  EditOrderStatusModalRef,
} from '@/pages/workOrderManagement/components/EditOrderStatusModal.tsx';
import dayjs from 'dayjs';
import { RoleType } from '@/hooks/useUserRole.ts';
import { ColumnType } from 'antd/es/table';

const WorkOrderManagement = () => {
  const catchFn = useCatch();
  const detailDrawerRef = useRef<DetailDrawerRef>(null);

  const [
    { data: headerOptions },
    { data: userHeaderOptions },
    { data: alarmTypeOptions },
    { data: reporterOptions },
  ] = useQueries({
    queries: [
      {
        queryKey: ['headerList'],
        queryFn: () => catchFn(() => WorkOrderServices.getHeaderList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            label: item.name,
            value: item.id,
          })),
      },
      {
        queryKey: ['userHeaderList'],
        queryFn: () => catchFn(() => WorkOrderServices.getUserHeaderList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            label: item.name,
            value: item.id,
          })),
      },
      {
        queryKey: ['alarmTypeList'],
        queryFn: () => catchFn(() => EventCenterServices.getAlarmTypeList()),
        select: ({ data }: Result<string[]>) => data.map((item) => ({ label: item, value: item })),
      },
      {
        queryKey: ['reporterList'],
        queryFn: () => catchFn(() => WorkOrderServices.getReporterList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            label: item.name,
            value: item.id,
          })),
      },
    ],
  });

  const userRole = useUserRole();

  const roleFields: Record<RoleType, string[]> = {
    header: [
      'name',
      'companyUserIdList',
      'departmentIdList',
      'alarmDesc',
      'reportPosition',
      'handleStatus',
    ],
    manager: [
      'name',
      'departmentIdList',
      'companyHeadIdList',
      'alarmDesc',
      'reportPosition',
      'handleStatus',
    ],
    tech: [
      'name',
      'companyUserIdList',
      'companyHeadIdList',
      'alarmDesc',
      'reportPosition',
      'handleStatus',
    ],
    none: [
      'name',
      'companyUserIdList',
      'departmentIdList',
      'companyHeadIdList',
      'alarmDesc',
      'reportPosition',
      'handleStatus',
    ],
  };

  const roleColumns: Record<RoleType, string[]> = {
    header: [
      'name',
      'time',
      'userName',
      'alarmDesc',
      'reportPosition',
      'reportName',
      'handleStatus',
      'action',
    ],
    manager: [
      'name',
      'time',
      'headName',
      'alarmDesc',
      'reportPosition',
      'reportName',
      'handleStatus',
      'action',
    ],
    tech: [
      'name',
      'time',
      'userName',
      'headName',
      'alarmDesc',
      'reportPosition',
      'handleStatus',
      'action',
    ],
    none: [
      'name',
      'time',
      'headName',
      'userName',
      'alarmDesc',
      'reportPosition',
      'reportName',
      'handleStatus',
      'action',
    ],
  };

  const fields: ITableProps<
    OrderInfo,
    OrderListParams & {
      companyUserIdList?: number;
      companyHeadIdList?: number;
      departmentIdList?: number;
    }
  >['fields'] = [
    {
      name: 'name',
      label: '工单名称',
      type: FormFieldType.Input,
    },
    {
      name: 'companyUserIdList',
      label: '项目经理',
      type: FormFieldType.Select,
      fieldProps: {
        options: userHeaderOptions,
      },
    },
    {
      name: 'departmentIdList',
      label: '上报部门',
      type: FormFieldType.Select,
      fieldProps: {
        options: reporterOptions,
      },
    },
    {
      name: 'companyHeadIdList',
      label: '养护负责人',
      type: FormFieldType.Select,
      fieldProps: {
        options: headerOptions,
      },
    },
    {
      name: 'alarmDesc',
      label: '病害类型',
      type: FormFieldType.Select,
      fieldProps: {
        options: alarmTypeOptions,
      },
    },
    {
      name: 'reportPosition',
      label: '上报位置',
      type: FormFieldType.Input,
    },
    {
      name: 'handleStatus',
      label: '处置状态',
      type: FormFieldType.Select,
      fieldProps: {
        options: [
          { label: '已完成', value: true },
          { label: '处置中', value: false },
        ],
      },
    },
  ];

  const columns: ITableProps<
    OrderInfo,
    OrderListParams & {
      companyUserIdList?: number;
      companyHeadIdList?: number;
      departmentIdList?: number;
    }
  >['columns'] = [
    {
      title: '工单名称',
      dataIndex: 'name',
      fixed: 'left',
      width: 200,
      ellipsis: true,
      render: (value) => <Tooltip title={value}>{value}</Tooltip>,
    },
    {
      title: '计划时间',
      dataIndex: 'time',
      width: 250,
      ellipsis: true,
      render: (_value, record) => (
        <Tooltip title={`${record.beginTime} - ${record.endTime}`}>
          {record.beginTime} - {record.endTime}
        </Tooltip>
      ),
    },
    { title: '项目经理', dataIndex: 'userName', width: 180, ellipsis: true },
    { title: '养护负责人', dataIndex: 'headName', width: 180, ellipsis: true },
    { title: '病害类型', dataIndex: 'alarmDesc', width: 120 },
    {
      title: '上报位置',
      dataIndex: 'reportPosition',
      width: 300,
      ellipsis: true,
      render: (value) => (
        <Tooltip title={value} placement="topLeft">
          {value}
        </Tooltip>
      ),
    },
    { title: '上报部门', dataIndex: 'reportName', width: 180, ellipsis: true },
    {
      title: '处置状态',
      dataIndex: 'handleStatus',
      width: 120,
      render: (value) => (value ? '已完成' : '处置中'),
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 150,
      render: (_value, record) => (
        <Space onClick={(e) => e.stopPropagation()}>
          {record.handleStatus ? null : (
            <PermissionGuard permissions={['WORK_ORDER_HANDLE']}>
              <Button
                type="link"
                size="small"
                onClick={() =>
                  modalRef.current?.open({
                    id: record.id,
                    date: [dayjs(record.beginTime), dayjs(record.endTime)],
                  })
                }
              >
                上报处置结果
              </Button>
            </PermissionGuard>
          )}
        </Space>
      ),
    },
  ];

  const fieldsByRole = useMemo(() => {
    const role = roleFields[userRole];
    return fields.filter((i) => role.includes(i.name));
  }, [userRole]);

  const columnsByROle = useMemo(() => {
    const role = roleColumns[userRole];
    return columns.filter((i: ColumnType<OrderInfo>) => role.includes(i.dataIndex as string));
  }, [userRole]);

  const tableProps: ITableProps<
    OrderInfo,
    OrderListParams & {
      companyUserIdList?: number;
      companyHeadIdList?: number;
      departmentIdList?: number;
    }
  > = {
    api: {
      key: ['workOrderList'],
      fn: async (params) => {
        const p: OrderListParams & Page = {
          page: params.page,
          limit: params.limit,
          order: params.order,
          name: params.name,
          alarmDesc: params.alarmDesc,
          reportPosition: params.reportPosition,
          handleStatus: params.handleStatus,
        };
        if (params.companyHeadIdList) p.companyHeadIdList = [params.companyHeadIdList];
        if (params.companyUserIdList) p.companyUserIdList = [params.companyUserIdList];
        if (params.departmentIdList) p.departmentIdList = [params.departmentIdList];
        const { data, total } = await WorkOrderServices.getList({ ...p });

        return {
          data,
          total: total ?? 0,
        };
      },
    },
    onRow: (record) => ({
      onClick: () => {
        detailDrawerRef.current?.open(record.id);
      },
    }),
    rowKey: 'id',
  };

  const tableRef = useRef<ITableRef>(null);
  const modalRef = useRef<EditOrderStatusModalRef>(null);

  return (
    <>
      <ITable {...tableProps} ref={tableRef} fields={fieldsByRole} columns={columnsByROle} />
      <DetailDrawer ref={detailDrawerRef} />
      <EditOrderStatusModal ref={modalRef} onSuccess={() => tableRef.current?.refetch()} />
    </>
  );
};

export default WorkOrderManagement;
